% plot_buffer_lifetimes_from_csv.m
% Plot buffer lifetimes from CSV data
function plot_buffer_lifetimes_from_csv(csv_file, output_dir, case_name)
    % Read CSV data
    data = readtable(csv_file);
    
    % Extract unique cache types
    cache_types = unique(data.cache_type);
    
    for ct = cache_types'
        % Filter data for current cache type
        type_data = data(data.cache_type == ct, :);
        
        if isempty(type_data)
            continue;
        end
        
        % Sort by buffer_id for better visualization
        type_data = sortrows(type_data, 'buffer_id');
        
        % Create figure
        fig = figure('Name', sprintf('Buffer Lifetimes - Cache Type %d', ct), ...
                     'Position', [100, 100, 1000, 600]);
        
        hold on;
        
        % Plot each buffer lifetime as a horizontal bar
        for i = 1:height(type_data)
            y_pos = i;
            start_step = type_data.start_step(i);
            end_step = type_data.end_step(i);
            
            % Draw lifetime bar
            patch([start_step, end_step, end_step, start_step], ...
                  [y_pos-0.4, y_pos-0.4, y_pos+0.4, y_pos+0.4], ...
                  'b', 'EdgeColor', 'k', 'LineWidth', 0.5);
            
            % Add buffer ID label
            text(start_step-5, y_pos, sprintf('Buf_%d', type_data.buffer_id(i)), ...
                 'FontSize', 8, 'HorizontalAlignment', 'right');
        end
        
        hold off;
        
        title(sprintf('Buffer Lifetimes - Cache Type %d', ct));
        xlabel('Step');
        ylabel('Buffer Index');
        ylim([0, height(type_data)+1]);
        grid on;
        
        % Save figure
        filename = sprintf('%s_buffer_lifetimes_cache%d.png', case_name, ct);
        filepath = fullfile(output_dir, filename);
        saveas(fig, filepath);
        
        fprintf('  Buffer lifetimes plot saved: %s\n', filepath);
        close(fig);
    end
end



